package com.codeboy.webshell.WebSocket.websocket;

import com.codeboy.webshell.WebSocket.service.WebSSHservice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import com.codeboy.webshell.WebSocket.constant.ConstantPool;

/**
 *
 * @Description :WebSSH的WebSocket处理器
 * @Author :崔昌赫
 * @Date :2021/9/12
 *
 */
@Component
public class WebSSHWebSocketHandler implements WebSocketHandler {
    @Autowired
    private WebSSHservice webSSHservice;
    private Logger logger = LoggerFactory.getLogger(WebSSHWebSocketHandler.class);

    /**
     * @Description :用户连接上WebSocket的回调
     * @param webSocketSession webSocket会话实例
     * @throws Exception 连接失败抛出错误
     * @Author :崔昌赫
     * @Date : 2021/9/12
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        logger.info("用户:{},连接WebSSH",webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY));
        webSSHservice.initConnection(webSocketSession);
    }

    /**
     * @Description :接受信息回调
     * @param webSocketSession  SSH会话实例
     * @param webSocketMessage  接收到的会话信息
     * @throws Exception 不正确信息报错
     * @Author :崔昌赫
     * @Date :2021/9/12
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        if(webSocketMessage instanceof TextMessage){
            logger.info("用户:{},发送命令:{}",webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY),((TextMessage) webSocketMessage).toString());
            webSSHservice.recvHandle(((TextMessage)webSocketMessage).getPayload(),webSocketSession);
        }else if (webSocketMessage instanceof BinaryMessage){

        }else if (webSocketMessage instanceof PongMessage){

        }else{
            logger.error("不可解析的WebSocket信息类型:"+webSocketMessage);
        }
    }

    /**
     * @Description :出现错误的回调
     * @param webSocketSession SSH会话实例
     * @param throwable 抛出的错位
     * @throws Exception 遇到无法处理错误抛出错误
     * @Author :崔昌赫
     * @Date :2020/9/12
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        logger.error("数据传输错误！");
    }

    /**
     * @Description :连接关闭回调
     * @param webSocketSession SSH会话实例
     * @param closeStatus 关闭状态
     * @throws Exception 无法正常关闭抛出错误
     * @Author :崔昌赫
     * @Date :2021/9/12
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        logger.info("用户:{}断开webssh连接",String.valueOf(webSocketSession.getAttributes().get(ConstantPool.USER_UUID_KEY)));
        webSSHservice.close(webSocketSession);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
